package com.github.shiqiyue.myadmin.controller.base;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.shiqiyue.myadmin.entity.SessionUser;
import com.github.shiqiyue.myadmin.entity.system.User;
import com.github.shiqiyue.myadmin.exception.ApplicationRuntimeException;
import com.github.shiqiyue.myadmin.util.date.DateUtil;
import com.github.shiqiyue.myadmin.util.security.SecurityUtils;
import com.github.shiqiyue.myadmin.util.web.AjaxUtils;
import com.github.shiqiyue.myadmin.vo.rep.base.RepBase;
import com.github.shiqiyue.myadmin.vo.rep.base.ResultCode;
import com.github.shiqiyue.myadmin.vo.req.page.ReqPageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/***
 * 后台管理控制器基类
 * 
 * @author wwy
 *
 */
public class AdminBaseController extends BaseController {
	
	@ExceptionHandler(value = Exception.class)
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		logger.error("应用异常" + DateUtil.getTime(), ex);
		ModelAndView mv = new ModelAndView();
		if (AjaxUtils.isAjaxRequest(request) || AjaxUtils.isAjaxUploadRequest(request)) {
			response.setContentType("application/json;charset=UTF-8");
            RepBase<String> rep = new RepBase<>();
			if (ex instanceof ApplicationRuntimeException) {
                rep.setCode(ResultCode.COMMON_FAIL).setMes(ex.getMessage());
			} else if (ex instanceof AccessDeniedException) {
                rep.setCode(ResultCode.AUTHORITY_ERROR).setMes(ResultCode.AUTHORITY_ERROR.getMes());
			} else {
                rep.setCode(ResultCode.COMMON_FAIL).setMes(ResultCode.COMMON_FAIL.getMes());
			}
			try {
                response.getWriter().print(JSON.toJSONString(rep));
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			if (ex instanceof ApplicationRuntimeException) {
				try {
					response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
				} catch (IOException e) {
				}
			} else if (ex instanceof AccessDeniedException) {
				try {
					response.sendError(HttpStatus.FORBIDDEN.value());
				} catch (IOException e) {
				}
			} else {
				try {
					response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
				} catch (IOException e) {
				}
			}

		}
		return mv;
	}
	
	/** 获取后台登录用户信息 */
	public SessionUser getLoginSessionUser() {
		SessionUser sessionUser = SecurityUtils.getSessionUser();
		if (sessionUser == null) {
			return null;
		}
		if (sessionUser.getUser() == null) {
			return null;
		}
		return sessionUser;
	}
	
	/***
	 * 获取后台登录用户
	 * 
	 * @return
	 */
	public User getLoginUser() {
		SessionUser sessionUser = getLoginSessionUser();
		if (sessionUser == null) {
			return null;
		}
		return sessionUser.getUser();
	}
	
	/** 获取后台登录用户Id */
	public String getLoginUserId() {
		SessionUser sessionUser = getLoginSessionUser();
		if (sessionUser == null) {
			return null;
		}
		if (StringUtils.isBlank(sessionUser.getUser().getId())) {
			return null;
		}
		return sessionUser.getUser().getId();
	}

    /***
     * 处理输入参数
     *
     * @param map
     */
    protected void processParams(Map<String, Object> map) {
        String sStartDate = (String) map.get("startDate");
        String sEndDate = (String) map.get("endDate");
        if (StringUtils.isBlank(sStartDate)) {
            map.put("startDate", null);
        } else {
            map.put("startDate", DateUtil.getStartTimeOfDate(sStartDate));
        }
        if (StringUtils.isBlank(sEndDate)) {
            map.put("endDate", null);
        } else {
            map.put("endDate", DateUtil.getEndTimeOfDate(sEndDate));
        }
    }


    /***
     * 处理分页参数
     *
     * @param pageVO
     * @return
     */
    protected Page processPage(ReqPageVO pageVO) {
        Page page = new Page<>(pageVO.getCurrent(), pageVO.getSize());
        if (StringUtils.isNotBlank(pageVO.getSortColumn())) {
            if ("desc".equals(pageVO.getSortDirection())) {
                page.setAsc(false);
                page.setOrderByField(pageVO.getSortColumn());
            } else {
                page.setAsc(true);
                page.setOrderByField(pageVO.getSortColumn());
            }
        }
        return page;
    }
}
